"""
ASGI config for demo project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'QAPlatform.settings')

http_application = get_asgi_application()


async def websocket_application(scope, receive, send):
    while True:
        event = await receive()
        if event['type'] == 'websocket.connect':
            # 收到建立WebSocket连接的消息
            await send({
                'type': 'websocket.accept'
            })
        elif event['type'] == 'websocket.disconnect':
            # 收到中断WebSocket连接的消息
            break
        elif event['type'] == 'websocket.receive':
            # 其它情况，正常的WebSocket消息
            if event['text'] == 'ping':
                await send({
                    'type': 'websocket.send',
                    'text': 'pong!'
                })
        else:
            pass


async def application(scope, receive, send):
    if scope['type'] == 'http':
        await http_application(scope, receive, send)
    elif scope['type'] == 'websocket':
        await websocket_application(scope, receive, send)
    else:
        raise NotImplementedError(f"Unknown scope type {scope['type']}")
